package org.polyforms.repository.spring;

import java.util.Set;

import org.polyforms.repository.spi.EntityHelper;
import org.polyforms.repository.spi.IdentifierHelper;
import org.polyforms.repository.spi.PersistenceProvider;
import org.polyforms.repository.spi.QueryParameterResolver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

/**
 * Configuration in Spring container for persistence providers.
 * 
 * @author Kuisong Tong
 * @since 1.0
 */
@Component
public final class PersistenceProviderConfiguration {
    private PersistenceProvider persistenceProvider;

    /**
     * Create an instance with corresponding {@link PersistenceProvider}.
     */
    @Autowired
    public PersistenceProviderConfiguration(final Set<PersistenceProvider> persistenceProviders) {
        for (final PersistenceProvider provider : persistenceProviders) {
            if (provider.matches()) {
                persistenceProvider = provider;
            }
        }
        if (persistenceProvider == null) {
            throw new IllegalArgumentException("No matched SPI Provider found in bean factory.");
        }
    }

    /**
     * Create a bean of {@link EntityHelper}.
     */
    @Bean
    public EntityHelper entityHelper() {
        return persistenceProvider.getEntityHelper();
    }

    /**
     * Create a bean of {@link IdentifierHelper}.
     */
    @Bean
    public IdentifierHelper identifierHelper() {
        return persistenceProvider.getIdentifierHelper();
    }

    /**
     * Create a bean of {@link QueryParameterResolver}.
     */
    @Bean
    public QueryParameterResolver queryParameterResolver() {
        return persistenceProvider.getQueryParameterResolver();
    }
}
